<script setup lang="ts">
  import { nextTick, Ref, ref, watch } from 'vue';
  import { FormInstance, Message, RequestOption } from '@arco-design/web-vue';
  import type { UploadRequest } from '@arco-design/web-vue/es/upload/interfaces';
  import { ArticleData } from '@/api/article/types';
  import 'aieditor/dist/style.css';
  import { getCategoryList } from '@/api/category';
  import { AiEditor } from 'aieditor';
  import { uploadFile } from '@/api/file';
  import { createArticle, editArticle, getArticleDetail } from '@/api/article';
  import { reject } from 'lodash';

  interface Category {
    id: number;
    name: string;
  }

  const emit = defineEmits(['saveSuccess']);
  const dialogVisiable = ref(false);
  const addForm: Ref<ArticleData | any> = ref({
    id: undefined,
    title: '',
    summary: '',
    content: '',
    author: '',
    category: null,
    tags: [],
    coverImage: '',
    coverImageName: '',
    seoTitle: '',
    seoDescription: '',
    seoKeywords: [],
    slug: '',
    isSticky: 0,
    allowComments: 1,
    source: 0,
    externalLink: '',
    isRecommended: 0,
  });

  const contentRef = ref();
  let aiEditor: AiEditor | null = null;
  const categoryList = ref<Category[]>([]);
  const formRules: FormInstance['rules'] = {
    name: [{ required: true, message: '角色名不能为空' }],
    code: [{ required: true, message: '编码不能为空' }],
  };
  const formRef = ref();
  const saveId = ref();

  watch(
    () => dialogVisiable.value,
    async (newValue) => {
      if (newValue) {
        const result = await getCategoryList();
        categoryList.value = result.data;
      }
    },
    { immediate: true },
  );

  const handleOpen = async () => {
    dialogVisiable.value = true;
    await nextTick(() => {
      aiEditor = new AiEditor({
        element: contentRef.value as Element,
        placeholder: '点击输入内容...',
        content: addForm.value.content,
        image: {
          uploader: async (file: File): Promise<Record<string, any>> => {
            const allowImgType = [
              'image/jpeg',
              'image/png',
              'image/jpg',
            ].includes(file.type);
            const isLt5M = file.size / 1024 / 1024 < 5;
            if (!allowImgType) {
              Message.error('图片只能是 PNG/JPG/JPEG 格式!');
              return reject(null);
            }
            if (!isLt5M) {
              Message.error('图片大小不能超过 5MB!');
              return reject(null);
            }
            const formData = new FormData();
            formData.append('file', file);
            formData.append('category', 'article-content');
            return uploadFile(formData);
          },
        },
      });
    });
  };

  // 修改这部分代码
  const uploadRequest = (async (option: RequestOption) => {
    const { onError, onSuccess, fileItem } = option;
    try {
      const allowImgType = [
        'image/jpeg',
        'image/png',
        'image/jpg',
        'image/webp',
      ].includes(fileItem.file?.type as string);
      const isLt5M = (fileItem.file?.size as number) / 1024 / 1024 < 5;

      if (!allowImgType) {
        Message.error('图片只能是 PNG/JPG/JPEG 格式!');
        onError('error');
        return;
      }

      if (!isLt5M) {
        Message.error('图片大小不能超过 5MB!');
        onError('error');
        return;
      }

      const formData = new FormData();
      formData.append('file', fileItem.file as File);
      formData.append('category', 'article-cover');

      const result = await uploadFile(formData);
      addForm.value.coverImage = result.data.src;
      addForm.value.coverImageName = result.data.alt;
      Message.success('上传成功');
      onSuccess(result.data);
    } catch (error) {
      onError(error);
    }
  }) as unknown as (option: RequestOption) => UploadRequest;

  const resetFields = () => {
    addForm.value = {
      id: undefined,
      title: '',
      summary: '',
      content: '',
      author: '',
      category: null,
      tags: [],
      coverImage: '',
      coverImageName: '',
      seoTitle: '',
      seoDescription: '',
      seoKeywords: '',
      slug: '',
      isSticky: 0,
      allowComments: 1,
      source: 0,
      externalLink: '',
      isRecommended: 0,
    };
  };

  const handleSave = async () => {
    addForm.value.content = aiEditor?.getHtml();
    if (saveId.value) {
      const result = await editArticle(addForm.value);
      Message.success(result.data);
    } else {
      const result = await createArticle(addForm.value);
      Message.success(result.data);
    }
    dialogVisiable.value = false;
    emit('saveSuccess');
  };

  const handleEdit = async (id: number) => {
    saveId.value = id;
    const result = await getArticleDetail(id);
    addForm.value = result.data;
    await handleOpen();
  };

  const handleCancel = () => {
    dialogVisiable.value = false;
  };

  const handleClose = () => {
    if (aiEditor) {
      aiEditor.destroy();
    }
    resetFields();
    saveId.value = undefined;
  };

  defineExpose({
    handleOpen,
    handleEdit,
  });
</script>

<template>
  <a-modal
    :visible="dialogVisiable"
    title-align="start"
    :ok-text="$t('modal.operation.save')"
    :cancel-text="$t('modal.operation.cancel')"
    unmount-on-close
    fullscreen
    @before-ok="handleSave"
    @close="handleClose"
    @cancel="handleCancel"
  >
    <template #title>
      {{
        saveId
          ? $t('searchTable.operation.edit')
          : $t('searchTable.operation.create')
      }}
    </template>
    <a-form ref="formRef" :rules="formRules" :model="addForm" auto-label-width>
      <a-row :gutter="16">
        <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="8" :xxl="6">
          <a-form-item field="coverImage" label="文章封面">
            <a-upload
              v-if="saveId"
              draggable
              action="/"
              list-type="picture"
              :limit="1"
              :custom-request="uploadRequest"
              :default-file-list="[
                {
                  uid: '-1',
                  name: `${addForm.coverImageName}`,
                  url: `${addForm.coverImage}`,
                },
              ]"
            />
            <a-upload
              v-else
              draggable
              action="/"
              list-type="picture"
              :limit="1"
              :custom-request="uploadRequest"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="8" :xxl="6">
          <a-form-item field="title" label="文章标题">
            <a-input
              v-model="addForm.title"
              allow-clear
              placeholder="请输入文章标题"
            />
          </a-form-item>
        </a-col>
        <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="8" :xxl="6">
          <a-form-item field="slug" label="文章别名">
            <a-input
              v-model="addForm.slug"
              allow-clear
              placeholder="请输入文章别名"
            />
          </a-form-item>
        </a-col>
        <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="8" :xxl="6">
          <a-form-item field="author" label="文章作者">
            <a-input
              v-model="addForm.author"
              allow-clear
              placeholder="请输入文章作者"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="8" :xxl="6">
          <a-form-item field="seoTitle" label="SEO标题">
            <a-input
              v-model="addForm.seoTitle"
              allow-clear
              placeholder="请输入SEO标题"
            />
          </a-form-item>
        </a-col>
        <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="8" :xxl="6">
          <a-form-item field="seoKeywords" label="SEO关键词">
            <a-input-tag
              v-model="addForm.seoKeywords"
              placeholder="请输入SEO关键词"
              allow-clear
            />
          </a-form-item>
        </a-col>
        <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="8" :xxl="6">
          <a-form-item field="seoDescription" label="SEO描述">
            <a-input
              v-model="addForm.seoDescription"
              allow-clear
              placeholder="请输入SEO描述"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="8" :xxl="6">
          <a-form-item field="category" label="分类">
            <a-select v-model="addForm.category" placeholder="请选择分类">
              <a-option
                v-for="item in categoryList"
                :key="item.id"
                :value="item.id"
              >
                {{ item.name }}
              </a-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="8" :xxl="6">
          <a-form-item field="tags" label="标签">
            <a-input-tag
              v-model="addForm.tags"
              placeholder="请输入标签"
              allow-clear
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="8" :xxl="6">
          <a-form-item field="isSticky" label="是否置顶">
            <a-switch
              v-model="addForm.isSticky"
              :checked-value="1"
              :unchecked-value="0"
              checked-text="是"
              unchecked-text="否"
              type="round"
            />
          </a-form-item>
        </a-col>
        <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="8" :xxl="6">
          <a-form-item field="allowComments" label="允许评论">
            <a-switch
              v-model="addForm.allowComments"
              :checked-value="1"
              :unchecked-value="0"
              checked-text="是"
              unchecked-text="否"
              type="round"
            />
          </a-form-item>
        </a-col>
        <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="8" :xxl="6">
          <a-form-item field="source" label="文章来源">
            <a-switch
              v-model="addForm.source"
              :checked-value="1"
              :unchecked-value="0"
              checked-text="转载"
              unchecked-text="原创"
              type="round"
            />
          </a-form-item>
        </a-col>
        <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="8" :xxl="6">
          <a-form-item field="isRecommended" label="是否推荐">
            <a-switch
              v-model="addForm.isRecommended"
              :checked-value="1"
              :unchecked-value="0"
              checked-text="是"
              unchecked-text="否"
              type="round"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="12">
          <a-form-item field="summary" label="文章摘要">
            <a-textarea
              v-model="addForm.summary"
              placeholder="请输入文章摘要"
              allow-clear
              show-word-limit
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" :xxl="24">
          <a-form-item field="content" label="文章内容">
            <div ref="contentRef" class="contentDiv" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<style scoped lang="less">
  .contentDiv {
    width: 100%;
    height: 375px;
  }
</style>
